<template>
	<div class="shopcart-container">
		<!-- 全选 清空 -->
		<div class="cart_header">
			<div class="cart_title">
				<!-- 全选 -->
				<van-checkbox checked-color="@mainColor" icon-size="18" v-model="isCheckedAll" @click="onSelectAll">全选
				</van-checkbox>
			</div>
			<div class="cart_clear" @click="onClickDeleteAll">
				<van-icon name="delete" />
				<span>清空</span>
			</div>
		</div>
		<!-- 商品列表区域 -->
		<div style="background-color: white;">
			<van-row v-for="(item, i) in cartList" :key="i" type="flex" align="center">
				<van-col span="2">
					<!-- 复选框 -->
					<van-checkbox v-model="item.checked" checked-color="@mainColor" @change="onCheckedChange(item)" />
				</van-col>
				<van-col span="5">
					<!-- 中间商品图片 -->
					<van-icon size="80" :name="item.productPic"></van-icon>
				</van-col>
				<van-col span="17">
					<van-row class="van-multi-ellipsis--l2 title">{{ item.productTitle}}</van-row>
					<van-row  type="flex" align="center">
						<van-col span="8" class="price">¥{{ item.productPrice }}</van-col>
						<van-col span="16" class="opration">
							<van-stepper v-model="item.count" @change="onCountChanged(item)" integer />
							<van-button text="删除" size="small" @click.prevent="onClickDeleteCartItem(item.id)" />
						</van-col>
					</van-row>
				</van-col>
			</van-row>
		</div>
		<!-- 商品结算区域 -->
		<van-cell title="商品结算" value="总计不含运费"></van-cell>
		<van-cell>
			<template #title>
				已勾选商品<span class="highlight">{{ getCheckedCount }}</span>件，总价<span class="highlight">¥{{ getCheckedAmount }}</span>
			</template>
		</van-cell>
		<!-- 结算按钮 -->
		<van-button type="primary" size="large" @click="onClickCreateOrder">去结算</van-button>
	</div>
</template>

<script>
	import {
		getCartListAPI,
		updateCartCountAPI,
		updateCartCheckedAPI,
		deleteCartItemAPI,
		deleteCartAllAPI, //删除清空购物车接口
		updateCartCheckedAllAPI, //全选/全不选购物车项接口
	} from "@/api/cart.js";
	import { showConfirmDialog, showToast } from 'vant';
	export default {
		data() {
			return {
				cartList: [], //购物车列表数据
				isCheckedAll: false, //是否全选
			};
		},
		//生命周期方法
		created() {
			this.getCartData();
		},
		//计算属性
		computed: {
			getCheckedCount() { //计算勾选记录总数
				let sum = 0;
				this.cartList.forEach((item) => {
					if (item.checked) sum += 1;
				});
				return sum;
			},
			getCheckedAll() { //计算是否全部勾选
				return this.cartList.length > 0 && this.cartList.length == this.getCheckedCount;
			},
			getCheckedAmount() { //计算勾选商品总金额
				let amount = 0;
				this.cartList.forEach((item) => {
					if (item.checked) amount += (item.productPrice || 0) * (item.count || 0);
				});
				return amount.toFixed(2);
			},
		},

		//方法定义
		methods: {
			//获取用户购物车数据
			getCartData() {
				this.cartList = []; //清空
				getCartListAPI().then(result => {
					if (result.data) {
						this.cartList = result.data;
						this.isCheckedAll = this.getCheckedAll; // 重置isCheckedAll属性值
					}
				}).catch((error) => {
					console.error("获取购物车数据失败:", error);
					showToast("获取购物车数据失败");
				});
			},

			//触发更改购物商品数量
			onCountChanged(item) {
				//准备参数
				let params = {
					id: item.id,
					count: item.count
				};
				//调用接口
				updateCartCountAPI(params).then(() => {
					// 更新成功后刷新数据
					this.getCartData();
				}).catch((error) => {
					console.error("更新商品数量失败:", error);
					showToast("更新商品数量失败");
					// 失败后恢复原值
					this.getCartData();
				});
			},

			//触发更改购物商品选中状态
			onCheckedChange(item) {
				let id = item.id;
				let checked = item.checked == true ? 1 : 0;
				let params = { id, is_checked: checked };
				updateCartCheckedAPI(params).then(() => {
					this.isCheckedAll = this.getCheckedAll; // 重置isCheckedAll属性值
				}).catch((error) => {
					console.error("更新选中状态失败:", error);
					showToast("更新选中状态失败");
					// 失败后恢复原值
					item.checked = !item.checked;
					this.getCartData();
				});
			},

			//触发删除购物商品
			onClickDeleteCartItem(id) {
				let ids = id;
				deleteCartItemAPI(ids).then(() => {
					showToast("删除成功");
					this.getCartData();
				}).catch((error) => {
					console.error("删除商品失败:", error);
					showToast("删除商品失败");
				});
			},
			//触发全选/全不选
			onSelectAll() {
				let checked = this.isCheckedAll == true ? 1 : 0;
				updateCartCheckedAllAPI(checked).then(() => {
					this.getCartData();
				}).catch((error) => {
					console.error("全选/全不选操作失败:", error);
					showToast("操作失败");
					this.getCartData();
				});
			},
			//触发清空
			onClickDeleteAll() {
				showConfirmDialog({
					message: '客官，您确定清空购物车吗?'
				}).then(() => {
					deleteCartAllAPI().then(() => {
						showToast("购物车已清空");
						this.getCartData();
					}).catch((error) => {
						console.error("清空购物车失败:", error);
						showToast("清空购物车失败");
					});
				}).catch(() => {
					// 用户取消操作
				});
			},

			//触发创建订单
			onClickCreateOrder() {
				if (this.cartList.length === 0) {
					showToast("您的购物车为空");
					return;
				}
				// 检查是否有勾选的商品
				if (this.getCheckedCount === 0) {
					showToast("请至少选择一件商品");
					return;
				}
				//跳转到创建订单页面（根据购物车创建）
				this.$router.push({
					name: "orderCreate"
				});
			},

		},
	};
</script>

<style lang="less" scoped>
	// 主题颜色变量（与其他页面保持一致）
	@mainColor: #8b4513; // 棕色主题色
	@bgColor: #f9f5ed; // 米黄色背景
	@lightBrown: #f5e8d0; // 浅棕色
	@darkBrown: #5a4a42; // 深棕色
	@priceRed: #e53935; // 价格红色

	.shopcart-container {
		padding: 0px 10px;
		margin-top: 50px;
		background-color: @bgColor;
		min-height: 100vh;

		.cart_header {
			padding: 10px;
			margin: 10px 0;
			height: 20px;
			background-color: white;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 8px;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		}

		.cart_clear {
			display: flex;
			align-items: center;
			color: @darkBrown;
			font-size: 14px;
			
			.van-icon {
				margin-right: 4px;
				color: @mainColor;
			}
		}
	}

	.van-checkbox {
		justify-content: center;
		color: @darkBrown;
		
		&__icon--checked .van-icon {
			background-color: @mainColor;
			border-color: @mainColor;
		}
	}

	.title {
		padding: 5px 5px;
		font-size: 12px;
		line-height: 20px;
		color: @darkBrown;
	}

	.price {
		padding-left: 10px;
		text-align: left;
		font-size: 16px;
		font-weight: bold;
		color: @priceRed;
		display: flex;
		align-items: center;
	}

	.opration {
		padding-right: 10px;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		
		.van-stepper {
			/deep/ .van-stepper__minus,
			/deep/ .van-stepper__plus {
				border-color: @lightBrown;
				color: @mainColor;
			}
			
			/deep/ .van-stepper__input {
				border-color: @lightBrown;
				color: @darkBrown;
			}
		}
		
		.van-button {
			color: @mainColor;
			margin-left: 10px;
		}
	}

	.highlight {
		color: @priceRed;
		font-weight: bold;
		font-size: 16px;
	}

	// 单元格样式调整
	/deep/ .van-cell {
		background-color: white;
		margin: 10px 0;
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		
		.van-cell__title {
			color: @darkBrown;
		}
	}

	// 结算按钮样式
	/deep/ .van-button--primary {
		background-color: @mainColor;
		border-color: @mainColor;
		color: white;
		margin: 15px 10px;
		border-radius: 8px;
		font-size: 16px;
		height: 48px;
		
		&:active {
			background-color: darken(@mainColor, 10%);
			border-color: darken(@mainColor, 10%);
		}
	}
</style>